package scheduler

import (
	"goruntimeDistributionCrawler/engine"
)

type QueuedScheduler struct {
	requestChan chan engine.Request
	worker chan chan engine.Request
}

func (s *QueuedScheduler) GetRequstChan() chan engine.Request {
		return make(chan engine.Request)
}

func (s *QueuedScheduler) Submit(r engine.Request) {
	s.requestChan<-r
}

func (s *QueuedScheduler) WorkerReady(
	w chan engine.Request)  {
	s.worker<-w
}

func (s *QueuedScheduler) Run()  {
	s.requestChan=make(chan engine.Request)
	s.worker=make(chan chan engine.Request)
	go func() {
		var requestQ []engine.Request
		var workerQ []chan engine.Request
		for{
			var activeReques engine.Request
			var activeWorker  chan engine.Request
            if len(requestQ)>0 &&
            	len(workerQ)>0{
               activeReques=requestQ[0]
               activeWorker=workerQ[0]
			}
			select {
			    case r:=<-s.requestChan:
			    	requestQ=append(requestQ,r)
				case w:=<-s.worker:
				    workerQ=append(workerQ,w)
			    case activeWorker<-activeReques:
			     	requestQ=requestQ[1:]
			     	workerQ=workerQ[1:]
			}
		}
	}()
}